package com.wonders.bigdata.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Description: 用一个buffer完成文件的读取<br>
 *
 * @author: XB
 * @date: 2021/5/6 9:39
 */
public class NIOFilechannel03 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("/file/netty/file02.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream outputStream = new FileOutputStream("/file/netty/file03.txt");
        FileChannel fileChannel02 = outputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) {
            // 这里有一个重要的操作，重置buffer
            byteBuffer.clear();

            int read = fileChannel01.read(byteBuffer);
            System.out.println("read = " + read);
            // 表示读完
            if (read == -1) {
                break;
            }
            // 将buffer中的数据写入到fileChannel02的文件中
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }
        // 关闭相关的流
        fileChannel01.close();
        fileChannel02.close();
        fileInputStream.close();
        outputStream.close();
    }
}
